"""
加载用户信息
加载商品信息
登录
注册
展示商品
...
"""
import os
import json
#__init__函数什么时候需要
#1.实例化对象的时候,不需要为这个实例单独赋值,可以省略__init__函数
#2.self.实例属性=形参
file_path_user = "user.txt"
class User():


    def __init__(self,username,password):
        self.auth = False
        self.login(username, password)

    def login(self,username,password):
        if os.path.exists(file_path_user):
            fp = open(file_path_user)
            user_str = fp.read()
            self.user_dict = json.loads(user_str)
        if username in self.user_dict and self.user_dict[username]["password"] == password:
            print(f"登录成功,欢迎{username}来到三乐购物中心!")
            self.auth = True
            self.username = username
            self.password = password
            self.balance = self.user_dict[username]["balance"]
        else:
            print("登录失败!")
    def show(self):
        if self.auth:
            print(f"当前登录的用户是：{self.username}")
        else:
            print("当前没有登录！")

    def save_money(self):
        ##装饰器优化该每个函数的重复代码
        money = int(input("请输入您想充值的数目:"))
        if self.auth:
            self.balance += money
            print(f"存钱成功!截止目前,您的余额为{self.balance}")
        else:
            print("您还未登录成功,请先登录!")

    def get_balance(self):
        if self.auth:
            print(f"截止目前,您的余额为{self.balance}")
        else:
            print("您还为登录成功,请先登录!")

    def logout(self, file_path_user):
        self.auth = False
        self.user_dict[self.username]["balance"] = self.balance
        fp = open(file_path_user, "w")
        # json.dumps 把一个对象转换成json格式的字符串
        # json.loads 把一个json格式的字符串转换成对象
        result_str = json.dumps(self.user_dict)
        fp.write(result_str)
        # 强制把写入内容从内存写入磁盘
        fp.flush()
        del self.username
        del self.balance
        del self.password
        print("退出成功!")
file_path_goods = "goods.txt"
class ShoppingSystem():
    MAX_LOGIN = 3
    def __init__(self):
        #自动从文件中加载用户数据和商品数据
        if os.path.exists(file_path_goods):
            fp = open(file_path_goods,encoding="utf-8")
            goods_str = fp.read()
            self.goods_dict = json.loads(goods_str)
        if os.path.exists(file_path_user):
            fp = open(file_path_user,encoding="utf-8")
            user_str = fp.read()
            self.user_dict = json.loads(user_str)
    def login(self):
        """登录"""
        print("-----登录-----")
        username = input("请输入用户名：")
        password = input("请输入密码：")
            # 实例化一个用户
        user = User(username, password)
        if user.auth:
            self.username = username
            self.password = password
            self.balance = self.user_dict[username]["balance"]
            self.current_user = user
            return True

    def regist(self):
        print("-------注册------")
        username = input("请输入用户名：")
        passwd = input("请输入密码：")
        re_passwd = input("请再次输入密码：")
        if passwd == re_passwd and username not in self.user_dict:
            self.user_dict[username] = {}
            self.user_dict[username]["password"] = passwd
            self.user_dict[username]["balance"] = 0
            fp = open(file_path_user, "w")
            # json.dumps 把一个对象转换成json格式的字符串
            # json.loads 把一个json格式的字符串转换成对象
            result_str = json.dumps(self.user_dict)
            fp.write(result_str)
            # 强制把写入内容从内存写入磁盘
            fp.flush()
            print("注册成功!请前往登录页面")
            return True
        elif passwd != re_passwd:
            print("两次密码输入不一致,请重新输入!")
        else:
            print("用户名已经被使用,请重新输入")

    def serch_goods(self):
        goods_id = input("请输入商品编号(001-003):")
        for i in self.goods_dict:
            if goods_id == i:
                print(f"商品编号:{i}--商品名称:{self.goods_dict[i]['name']}--价格:{self.goods_dict[i]['price']}")
    def add_shop(self):
        goods_id = input("请输入想要添加至购物车的商品编号(001-003):")
        self.shop_dict = {}
        self.shop_dict[goods_id] = {}
        self.shop_dict[goods_id]["name"] = self.goods_dict[goods_id]["name"]
        self.shop_dict[goods_id]["price"] = self.goods_dict[goods_id]["price"]
        print(f"添加商品{self.shop_dict[goods_id]['name']}成功!")
    def buy_shop(self):
        sum = 0
        for i in self.shop_dict:
            sum += self.shop_dict[i]["price"]
        if sum > self.balance:
            print("余额不足,请先充值!")
        else:
            self.balance -= sum
            print(f"支付成功,共计{sum}元,您的余额还剩{self.balance}元")
    def logout(self):
        self.auth = False
        self.user_dict[self.username]["balance"] = self.balance
        fp = open(file_path_user, "w")
        # json.dumps 把一个对象转换成json格式的字符串
        # json.loads 把一个json格式的字符串转换成对象
        result_str = json.dumps(self.user_dict)
        fp.write(result_str)
        # 强制把写入内容从内存写入磁盘
        fp.flush()
        del self.username
        del self.balance
        del self.password
        print("退出成功!")

    def start(self):
        # 登录成功：
        #       1、查看商品
        #       2、加入购物车
        #       3、结算购物车
        #       4、返回上一级
        menu_data = """
        1.查看商品
        2.加入购物车
        3.结算购物车
        4.查看余额
        5.充值
        6.退出
        """
        x = input("是否已有账号?(1--有/2--无)")
        if x == "1":
            count = 0
            while True:
                count = count + 1
                if count == 3:
                    print("登录次数用尽!")
                    break
                if self.login():
                    break
        else:
            while True:
                if self.regist():
                    break
            count = 0
            while True:
                count = count+1
                if count == 3:
                    print("登录次数用尽!")
                    break
                if self.login():
                    break
        try:
            menu_func = {"1":self.serch_goods,
                         "2":self.add_shop,
                         "3": self.buy_shop,
                         "6": self.logout,
                         "4":self.current_user.get_balance,
                         "5":self.current_user.save_money}
            # 当前没有用户登录 ：None，登录了，就是当前用户实例

            while True:
                if self.current_user:
                    print(menu_data)
                    choice = input("请输入您的操作:")
                    menu_func[choice]()
                    if choice == '6':
                        break
        except AttributeError as ex:
            print("")
        except KeyError as ex:
            print("没有这个操作选项,您再仔细看看呢")


sc_shoppingsystem = ShoppingSystem()
sc_shoppingsystem.start()